package com.cqs.leetcode.ds.union.find;

public class QuickFind implements IUnionFind {

    //节点ｉ所属的联通分量
    private int ids[];

    //联通分量数
    private int count;

    public QuickFind(int n) {
        ids = new int[n];
        for (int i = 0; i < n; i++) {
            ids[i] = i;
        }
        count = n;
    }

    @Override
    public int find(int p) {
        return ids[p];
    }

    @Override
    public void union(int p, int q) {
        int pid = find(p);
        int qid = find(q);
        if (pid == qid) return;
        for (int i = 0; i < ids.length; i++) {
            if (ids[i] == qid) ids[i] = pid;
        }
        --count;
    }

    @Override
    public int count() {
        return count;
    }

    @Override
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }
}
